using System;
using System.Data;
using Firestarter.DB.Schema.Logic;
using Habanero.Base;
using Habanero.DB;

namespace Firestarter.DB.Schema.Test.Logic
{
    public class TestUtilsDB_MySql : TestUtilsDB
    {
        private IDatabaseConnection _masterDatabaseConnection;

        public override DatabaseConfig CreateTestDatabaseConfig()
        {
            return new DatabaseConfig("Mysql", "localhost", TestDatabaseName, "root", "root", null);
        }

        protected override DatabaseConfig CreateMasterDatabaseConfig()
        {
            return new DatabaseConfig("Mysql", "localhost", "information_schema", "root", "root", null);
        }

        public override CreateTableSqlBuilder CreateSqlBuilderCreateTable(string tableName)
        {
            return new CreateTableSqlBuilder_MySql(tableName);
        }

        public override void CreateTestDatabase()
        {
            if (_masterDatabaseConnection == null)
            {
                _masterDatabaseConnection = CreateMasterDatabaseConfig().GetDatabaseConnection();
            }

            _masterDatabaseConnection.ExecuteRawSql(string.Format("DROP DATABASE IF EXISTS {0};", TestDatabaseName));
            _masterDatabaseConnection.ExecuteRawSql(
                string.Format(
                    @"
                    CREATE DATABASE IF NOT EXISTS {0};
                    USE {0};
                    ",
                    TestDatabaseName));
//            IDbConnection connection = _masterDatabaseConnection.GetConnection();
//            //if (connection.State == ConnectionState.Closed) connection.Open();
//            ExecuteSql(connection, string.Format("DROP DATABASE IF EXISTS {0};", TestDatabaseName));
//            ExecuteSql(connection, string.Format(@"
//                    CREATE DATABASE IF NOT EXISTS {0};
//                    USE {0};
//                    ", TestDatabaseName));
        }

        public override void ClearDatabase(IDbConnection connection)
        {
            string sqlStatement = string.Format
                (@"
                DROP DATABASE {0};
                CREATE DATABASE {0};
                USE {0};
                ",
                 TestDatabaseName);
            ExecuteSql(connection, sqlStatement);
        }

        public override void DropDatabase()
        {
            var masterConnection = this.CreateMasterConnection();

            using (masterConnection)
            {
                masterConnection.Open();
                ExecuteSql(masterConnection, string.Format(@"DROP DATABASE IF EXISTS {0};", TestDatabaseName));
            }
        }
    }
}